/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.transas.zornav.data;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author amalikov
 */
public class DataSource {

	public DataSource() {
		size = 0;
		table = new ArrayList<Column>();
	}
	
	public Object getHandle(String name) {
		for (Column col : table)
			if (col.name.equals(name))
				return col;
		return null;
	}

	public double getValue(Object handle, int index) {
		Column col = (Column)handle;
		return (index < size) ? col.values.get(index) : 0;
	}

	public String getValueAsString(Object handle, int index) {
		Column col = (Column)handle;
		return col.formatter.get(getValue(col, index));
	}

	public List<String> getNames() {
		List<String> names = new ArrayList<String>();
		for (Column col : table) {
			names.add(col.name);
		}
		return names;
	}

	public int getSize() {
		return size;
	}
	
	public void addColumn(String name, Formatter formatter) {
		Column col = (Column)getHandle(name);
		
		if (col == null)
			table.add(new Column(name, formatter, size));
		else
			col.formatter = formatter;
	}
	
	public void addRow() {
		for (Column col : table)
			col.values.add(new Double(0));
		++size;
	}
	
	public void removeRow(int row) {
		if (row >= 0 && row < size) {
			for (Column col : table)
				col.values.remove(row);
			--size;
		}
	}
	
	public void setValue(Object handle, int index, double value) {
		if (index < size) {
			Column col = (Column)handle;
			col.values.set(index, new Double(value));
		}
	}
	
	private class Column {
		public Column(String name, Formatter formatter, int size) {
			this.name = name;
			this.formatter = formatter;
			values = new ArrayList<Double>(size);
			for (int i = 0; i < size; ++i)
				values.add(new Double(0));
		}
		
		public String name;
		public Formatter formatter;
		public List<Double> values;
	}
	
	private List<Column> table;
	private int size;
}
